package com.yc.blog.util;

import biz.BizException;
import org.springframework.core.io.buffer.DataBuffer;
import reactor.core.publisher.Flux;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class Utils {

    public static void chcek(boolean bool, String msg) {
        if (bool) throw new BizException(msg);
    }

    public static void chcekEmpty(Object value, String msg) {
        chcek(isEmpty(value), msg);
    }

    public static boolean isEmpty(Object value) {
        boolean bool = false;
        if (value == null) bool = true;
        else if (value instanceof String) {
            bool = ((String) value).isBlank();
        } else if (value instanceof Collection<?>) {
            bool = ((Collection<?>) value).isEmpty();
        } else if (value instanceof Map<?, ?>) {
            bool = ((Map<?, ?>) value).isEmpty();
        }
        return bool;
    }

    /**
     * 数组转 map 集合
     * @param values
     * @return
     * @param <K>
     * @param <V>
     */
    public static <K, V> Map<K, V> asMap(Object... values) {
        Map<K, V> map = new HashMap<K, V>();
        for (int i = 0; i < values.length; i += 2) {
            if (i < values.length - 1) {
                map.put((K) values[i], (V) values[i + 1]);
            } else if (i == values.length - 1) {
                map.put((K) values[i], (V) values[i]);
            }
        }
        return map;
    }

    public static void saveFile(Flux<DataBuffer> flux, String path, boolean append) {
        try {
            FileOutputStream fos = new FileOutputStream(path, append);
            FileChannel ochannel = fos.getChannel();
            flux.doFinally(st->{
                try{
                    ochannel.close();
                    fos.close();
                }catch (IOException e){
                    throw new RuntimeException("关闭文件失败!",e);
                }
            }).subscribe(db->{
                db.readableByteBuffers().forEachRemaining(bf->{
                    try {
                        ochannel.write(bf);
                    } catch (IOException e) {
                        throw new RuntimeException("写入文件失败!",e);
                    }
                });
            });
        } catch (FileNotFoundException e) {
            throw new RuntimeException("打开文件失败!",e);
        }

    }
}
